// 将codeup不用uiless组件新建MR,代码首次同步到此处，分开维护，不同步修改（uiless接口经常有问题）
import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Message, Field, Select } from '@teamix/ui';
import { YunxiaoIcon, Title } from '@alife/devops-ui';
import MdEditor from 'components/mdEditor';
import MemberTrigger from 'components/memberTrigger';
import exceed from 'utils/apimap';
import { ENUM, ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import PathEllipsis from 'components/pathEllipsis';
import AssociatePanel from '@alife/yunxiao-create-mr-associate';
import utils from 'utils';
import './index.scss';
import track from 'utils/track';
import { getRecentPushApi } from 'api';
import intl from '../../../locale';
import { getFeature } from 'utils/features';

const prefix = 'uiless-create-mr-modal';
const { getGroupPath } = utils;

export default class CRModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    onCreateSuccess: PropTypes.func, // 创建成功的回调
    onCloseModal: PropTypes.func,
    defaultProjectId: PropTypes.string,
    defaultSourceBranch: PropTypes.string,
    defaultTargetBranch: PropTypes.string,
    title: PropTypes.string,
    isModalOpen: PropTypes.bool,
    cannotChangeProject: PropTypes.bool, // 是否禁用库选择器
    isCherryPick: PropTypes.bool,
    desc: PropTypes.string,
    extraRequestData: PropTypes.object, // 额外携带的参数
  };

  static defaultProps = {
    trigger: null,
    onCreateSuccess: () => {},
    onCloseModal: () => {},
    defaultProjectId: '',
    defaultSourceBranch: '',
    defaultTargetBranch: '',
    cannotChangeProject: false,
    // cherry-pick需要自定义标题和描述
    isCherryPick: false,
    desc: '',
    extraRequestData: {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);

    const source_branch = this.props.defaultSourceBranch || '';
    const title = this.props.title || '';
    const description = this.props.desc || '';

    this.state = {
      isModalOpen: false,
      projects: [],
      projectId: null,
      projectPath: null,
      branches: [],
      source_branch,
      title,
      target_branch: '',
      assigneeIdDataSource: [],
      description,
      checkMes: '',
      submitting: false,
      workitem_ids: '',
      is_enable_reviewer_recommend: false,
      source_branch_sha: null,
      target_branch_sha: null,
      defaultReviewerList: [],
      projectIdError: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  componentDidMount() {
    const { defaultProjectId, defaultTargetBranch, defaultSourceBranch } = this.props;
    // 是否默认当前库：空库可以默认当前库（错误提示 + 按钮禁用），浏览者权限则不默认当前库。
    if (defaultProjectId) {
      this.getRepoInfo(defaultProjectId, (projectInfo) => {
        // 非企业管理员 + access_level <= 20 则为浏览者
        // TODO organization.user_role怎么拿？
        const organization = {};
        const hasAccess =
          access(ORGANIZATION_ADMIN_ROLES, organization.user_role) ||
          Number(projectInfo.access_level) > ENUM.access_level_id.REPORTER;
        if (hasAccess) {
          this.setState({
            projectId: Number(defaultProjectId),
            projectPath: projectInfo.name_with_namespace,
          });

          // 库内吊顶需要请求所有列表，库内其他不需要
          if (!this.props.cannotChangeProject) {
            this.getAllProjects('', projectInfo);
          }
          if (defaultTargetBranch) {
            const target_branch = defaultTargetBranch;
            // 设置目标分支
            this.field.setValue('target_branch', target_branch);
            this.onTargetBranchChange(target_branch);
            this.getBranches(defaultProjectId, (branches) => {
              if (!defaultSourceBranch) {
                this.setSrcBranchByRecentPush(defaultProjectId, branches, defaultTargetBranch);
              }
            });
          } else {
            this.getBranches(defaultProjectId, (branches) => {
              this.setTargetBranch(projectInfo);
              if (!defaultSourceBranch) {
                this.setSrcBranchByRecentPush(
                  defaultProjectId,
                  branches,
                  projectInfo.default_branch,
                );
              }
            });
          }

          this.getMergeRequestSetting(defaultProjectId, (mrSetting) => {
            this.setState({
              is_enable_reviewer_recommend: mrSetting.is_enable_reviewer_recommend,
            });
          });
        } else {
          this.getAllProjects();
        }
      });
    } else {
      this.getAllProjects();
    }
  }

  // 根据最近提交设置源分支,
  setSrcBranchByRecentPush = (projectId, branches, targetBranch) => {
    getRecentPushApi(projectId, { per_page: 1, page: 1 }).then((recentPush) => {
      recentPush.shift();
      const { dataMap } = recentPush[0] || {};
      const ref = dataMap && dataMap[':ref'];
      const src_branch = ref && ref.replace('refs/heads/', '');
      const target_branch = targetBranch || 'master';
      // 有效分支切和默认目标分支不一致则设置
      if (src_branch !== target_branch && branches.find((br) => br.name === src_branch)) {
        this.field.setValue('source_branch', src_branch);
        this.onSourceBranchSelect(src_branch);
      }
    });
  };

  // 获取库权限，浏览者不默认当前库
  getRepoInfo = (projectId, callback) => {
    exceed
      .fetch({
        api: 'projects.single.get',
        params: { id: projectId },
      })
      .then((res) => {
        callback(res);
      })
      .fail((res) => {
        if (res.data && !res.data.success) {
          const { result } = res.data;
          Message.error({
            title: result ? result.message : res.data.message,
          });
        }
      });
  };

  // 获取合并请求设置
  getMergeRequestSetting = (projectId, callback) => {
    exceed
      .fetch({
        api: 'project.settings.merge_requests.get',
        params: { id: projectId },
      })
      .then((res) => {
        callback(res);
      })
      .fail((res) => {
        console.log(res);
      });
  };

  // 获取推荐评审人
  getRecommendReviewers = (projectId, sourceBranchSha, targetBranchSha, callback) => {
    if (projectId === null) {
      callback([]);
      return;
    }

    const data = {};
    if (sourceBranchSha) {
      data.source_version = sourceBranchSha;
    }

    if (targetBranchSha) {
      data.target_version = targetBranchSha;
    }

    exceed
      .fetch({
        api: 'merge_request.reviewer_recommend.get',
        params: {
          projectId,
        },

        data,
      })
      .then((res) => {
        res.shift();
        const list = res.sort((a, b) => {
          return b.score - a.score;
        });
        callback(list);
      })
      .fail((res) => {
        console.log(res);
      });
  };

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.onCloseModal();
  };

  onDialogOk = () => {
    if (this.state.submitting) return;
    const { extraRequestData } = this.props;
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        let formData = this.field.getValues();
        const { source_branch, target_branch, description, workitem_ids, projectId } = this.state;
        if (formData.tb_user_ids) {
          formData.tb_user_ids = formData.tb_user_ids.join(',');
        }

        formData = {
          ...extraRequestData,
          ...formData,
          description,
          source_branch,
          target_branch,
          workitem_ids,
          target_project_id: projectId,
        };

        this.createCr(formData, () => {
          this.setState({ submitting: false });
        });
      }
    });
  };

  onSourceBranchSelect = (value) => {
    this.setState({ source_branch: value });
    const selectedBranches = this.state.branches.filter((b) => b.name === value);
    if (selectedBranches && selectedBranches.length !== 0) {
      let title = selectedBranches[0].commit.message;
      const sourceSha = selectedBranches[0].commit.id;
      if (title.length > 128) {
        title = `${title.substr(0, 125)}...`;
      }
      this.setState(
        {
          title,
          source_branch_sha: sourceSha,
        },
        function () {
          this.checkRecommendReviewers();
        },
      );
      this.field.setValue('title', title);
      this.field.validate();
    } else {
      // Regard this is a SHA
    }
  };

  onProjectSelect = (value) => {
    const selectedProjects = this.state.projects.filter((p) => p.id === value);
    if (selectedProjects && selectedProjects.length) {
      const selectedProject = selectedProjects[0];
      this.setState({
        projectId: value,
        projectPath: selectedProject.name_with_namespace,
      });

      this.getRepoInfo(selectedProject.id, (projectInfo) => {
        this.getBranches(selectedProject.id, (branches) => {
          this.setTargetBranch(projectInfo);
          this.setSrcBranchByRecentPush(selectedProject.id, branches);
        });
      });

      this.getMergeRequestSetting(selectedProject.id, (mrSetting) => {
        this.setState({
          is_enable_reviewer_recommend: mrSetting.is_enable_reviewer_recommend,
        });
      });
    }
  };

  // 搜索代码库并获取列表
  onProjectSearch = (search) => {
    exceed
      .fetch({
        api: 'projects.getAuthWriteList',
        data: {
          search,
          per_page: 50,
          order_by: 'last_activity_at',
          sort: 'desc',
        },
      })
      .then((res) => {
        res.shift();
        this.setState({
          projects: res,
        });
      });
  };

  // 获取分支
  getBranches = (projectId, callback) => {
    exceed
      .fetch({
        api: 'projects.all.branches.search',
        params: { id: projectId },
      })
      .then((result) => {
        result.shift();
        if (result.length) {
          this.setState({
            branches: result,
            isEmpty: false,
          });

          // 在分支页面创建代码评审的场景，查询分支ok后，再设置默认分支
          callback && callback(result);
          if (this.state.source_branch) {
            this.onSourceBranchSelect(this.state.source_branch);
          }
          if (!this.state.projectIdError) {
            this.field.setError('projectId', '');
          }
        } else {
          this.setState({
            isEmpty: true,
          });

          // 返回数据为[]则为空库，重置数据
          const source_branch = this.props.defaultSourceBranch || '';
          const title = this.props.title || '';
          this.setState({
            branches: [],
            source_branch,
            title,
            target_branch: '',
            assigneeIdDataSource: [],
            checkMes: '',
          });

          this.field.setValue('target_branch', '');
          this.field.setValue('source_branch', '');
          this.field.setValue('title', '');
          if (!this.state.projectIdError) {
            this.field.setError(
              'projectId',
              intl.get({
                id: 'code-assets.createCRModal.uiless-create-mr-modal.TheSelectedDatabaseIsEmpty',
                defaultMessage: '所选库为空库，不能创建合并请求',
              }),
            );
          }
          this.field.setValue('tb_user_ids', []);
        }
      });
  };

  setTargetBranch = (projectInfo) => {
    const target_branch = projectInfo.default_branch || 'master';
    // 设置默认分支
    this.field.setValue('target_branch', target_branch);
    this.onTargetBranchChange(target_branch);
  };

  // 全局下获取代码库 curProjectInfo存在时，判断返回数据是否包含当前库，没有则将当前库放在首位
  getAllProjects = (search = '', curProjectInfo) => {
    exceed
      .fetch({
        api: 'projects.getAuthWriteList',
        data: {
          search,
          per_page: 50,
          order_by: 'last_activity_at',
          sort: 'desc',
        },
      })
      .then((result) => {
        result.shift();
        if (curProjectInfo) {
          if (result.findIndex((item) => item.id === curProjectInfo.id) === -1) {
            result.unshift(curProjectInfo);
          }
          this.field.setValue('projectId', Number(curProjectInfo.id));
        }
        this.setState({
          projects: result,
        });
      });
  };

  // 获取并设置默认评审人
  getCodeReviewSetting = (projectId, branch) => {
    exceed
      .fetch({
        api: 'codereview.setting.get',
        params: {
          id: projectId,
        },

        data: {
          branch,
        },
      })
      .then((result) => {
        this.setState(
          {
            assigneeIdDataSource: result.default_assignees,
          },

          () => {
            this.checkReviewer({
              tb_user_ids: result.default_assignees.map((item) => item.tb_user_id).join(','),
              target_branch: branch,
            });
          },
        );

        this.field.setValue(
          'tb_user_ids',
          result.default_assignees.map((item) => item.tb_user_id),
        );
      });
  };

  // 代码库搜索框
  getProjectFormItemJsx() {
    const { init } = this.field;
    const { cannotChangeProject } = this.props;
    const { projectPath } = this.state;
    let result = <Input />;
    if (cannotChangeProject) {
      const path = projectPath ? getGroupPath(projectPath) : '';
      result = <Input readOnly disabled value={path || ''} />;
    } else {
      result = (
        <Select
          autoWidth
          showSearch
          placeholder={intl.get({
            id: 'code-assets.createCRModal.uiless-create-mr-modal.EnterACodeLibraryName',
            defaultMessage: '请输入代码库名以搜索',
          })}
          dataSource={this.state.projects.map((p) => ({
            label: getGroupPath(p.path_with_namespace),
            value: p.id,
            name_with_namespace: getGroupPath(p.name_with_namespace),
          }))}
          onSearch={this.onProjectSearch}
          filterLocal={false}
          {...init('projectId', {
            initValue: this.state.projectId,
            rules: [
              {
                required: true,
                message: intl.get({
                  id: 'code-assets.createCRModal.uiless-create-mr-modal.ThisParameterIsRequired',
                  defaultMessage: '该项为必填项',
                }),
              },
              { validator: this.projectValidator },
            ],
            props: {
              onChange: (value) => {
                this.onProjectSelect(value);
              },
            },
          })}
          popupProps={{
            className: 'at-path-select-popup',
          }}
          itemRender={(item) => {
            const path = item.name_with_namespace;
            return <PathEllipsis path={path} />;
          }}
        />
      );
    }

    return result;
  }

  onChangevalue = (value) => {
    this.setState({ description: value });
  };

  onTargetBranchChange = (value) => {
    this.setState({ target_branch: value });
    const selectedBranches = this.state.branches.filter((b) => b.name === value);
    if (selectedBranches && selectedBranches.length !== 0) {
      const targetBranchSha = selectedBranches[0].commit.id;
      this.setState(
        {
          target_branch_sha: targetBranchSha,
        },
        function () {
          this.checkRecommendReviewers();
        },
      );
    }
    this.getCodeReviewSetting(this.state.projectId || this.props.defaultProjectId, value);
  };

  checkRecommendReviewers = () => {
    const { projectId, source_branch_sha, target_branch_sha, is_enable_reviewer_recommend } =
      this.state;

    if (!is_enable_reviewer_recommend) {
      return;
    }

    if (!projectId) {
      this.setState({
        defaultReviewerList: [],
      });
    }

    this.getRecommendReviewers(projectId, source_branch_sha, target_branch_sha, (result) => {
      this.setState({
        defaultReviewerList: result,
      });
    });
  };

  onMemberChange = (value) => {
    this.setState(
      {
        assigneeIdDataSource: value,
      },

      () => {
        this.checkReviewer({
          tb_user_ids: value.map((item) => item._userId || item.tb_user_id).join(','),
          target_branch: this.state.target_branch,
        });
      },
    );

    this.field.setValue(
      'tb_user_ids',
      value.map((item) => item._userId || item.tb_user_id),
    );
  };

  // 校验可点通过的评审者是否>=添加的评审者
  checkReviewer(data) {
    exceed
      .fetch({
        api: 'project.mr.check_reviewer',
        params: {
          projectId: this.state.projectId,
        },

        data: { ...data, lazy_init: true },
      })
      .then((result) => {
        if (result.pass === false) {
          this.setState({
            checkMes: result,
          });
        } else {
          this.setState({
            checkMes: '',
          });
        }
      });
  }

  // 创建CR
  createCr(formData, cb) {
    exceed
      .fetch({
        api: 'project.mr.post',
        params: {
          projectId: this.state.projectId,
        },

        data: { ...formData, lazy_init: true },
      })
      .then((cr) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.createCRModal.uiless-create-mr-modal.ReviewedAndCreated',
            defaultMessage: '评审新建成功',
          }),
        });

        cb && cb();

        const recommend_reviewers = this.state.defaultReviewerList.filter((item) => {
          return (
            item.tag &&
            item.tag.children ===
              intl.get({
                id: 'code-assets.createCRModal.uiless-create-mr-modal.Recommended',
                defaultMessage: '推荐',
              })
          );
        });

        const cur_recommend_reviewers = recommend_reviewers.map((item) => {
          return {
            user_id: item.id,
            score: item.score,
          };
        });
        const cur_assignees = cr.assignees.map((item) => {
          return {
            user_id: item.id,
          };
        });
        // 埋点
        track({
          action: 'reviewer_recommend',
          page: 'Repo-MR-Create',
          type: '',
          control: '',
          mr_id: cr.id,
          user_id: window.FORCE.user ? window.FORCE.user.id : '',
          code_user_id: window.FORCE.user ? window.FORCE.user.codeUserId : '',
          recommend_reviewers: JSON.stringify(cur_recommend_reviewers),
          assignees: JSON.stringify(cur_assignees),
        });

        this.onClose();
        // TODO 这里返回直接将cr对象返回，还是返回拼好的链接存疑
        this.props.onCreateSuccess(cr);
      })
      .fail(() => {
        cb && cb();
      });
  }

  // 合并请求名称校验
  nameValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 256) {
      callback(
        intl.get({
          id: 'code-assets.createCRModal.uiless-create-mr-modal.TheMergeRequestNameCannot',
          defaultMessage: '合并请求名称不能超过256字符',
        }),
      );
    } else {
      callback();
    }
  };

  projectValidator = (rule, value, callback) => {
    const { projects } = this.state;
    const current = projects.filter((i) => i.id === value)[0];
    if (current && current.archived) {
      this.setState({
        projectIdError: true,
      });
      callback('所选库已归档，不能创建合并请求');
    } else {
      this.setState({
        projectIdError: false,
      });
      callback();
    }
  };

  render() {
    const { field } = this;
    const { init } = this.field;
    const { checkMes, projectId, isEmpty, defaultReviewerList } = this.state;
    const { className, uiless_config, title, ...others } = this.props;
    return (
      <React.Fragment {...others}>
        {this.state.isModalOpen ? (
          <Dialog
            visible
            className={`${prefix} ${className || ''}`}
            onOk={this.onDialogOk}
            onCancel={this.onClose}
            onClose={this.onClose}
            title={intl.get({
              id: 'code-assets.createCRModal.uiless-create-mr-modal.CreateMergeRequest',
              defaultMessage: '新建合并请求',
            })}
            okProps={{ loading: this.state.submitting, disabled: isEmpty }}
            style={{
              width: 680,
            }}
            // {...others}
          >
            <Form className={`${prefix}-form`} field={field} labelAlign="top">
              <Form.Item
                label={intl.get({
                  id: 'code-assets.createCRModal.uiless-create-mr-modal.CodeBase',
                  defaultMessage: '代码库',
                })}
                className="cr-repo"
                required
              >
                {this.getProjectFormItemJsx()}
              </Form.Item>
              <div className={`${prefix}-form-branches`}>
                <Form.Item
                  label={intl.get({
                    id: 'code-assets.createCRModal.uiless-create-mr-modal.SourceBranch',
                    defaultMessage: '源分支',
                  })}
                  className="cr-source-branch"
                  required
                >
                  <Select
                    showSearch
                    dataSource={this.state.branches.map((item) => ({
                      label: item.name,
                      value: item.name,
                    }))}
                    {...init('source_branch', {
                      initValue: this.state.source_branch,
                      rules: [
                        {
                          required: true,
                          message: intl.get({
                            id: 'code-assets.createCRModal.uiless-create-mr-modal.ThisParameterIsRequired',
                            defaultMessage: '该项为必填项',
                          }),
                        },
                      ],
                      props: {
                        onChange: (value) => {
                          this.onSourceBranchSelect(value);
                        },
                      },
                    })}
                    popupProps={{
                      className: 'ellipsis-label-select-popup',
                    }}
                    itemRender={(item) => {
                      return (
                        <Title trigger={<span>{item.label}</span>} align="t">
                          {item.label}
                        </Title>
                      );
                    }}
                  />
                </Form.Item>
                <YunxiaoIcon type="arrow-right-line" className="cr-branch-icon" />

                <Form.Item
                  label={intl.get({
                    id: 'code-assets.createCRModal.uiless-create-mr-modal.TargetBranch',
                    defaultMessage: '目标分支',
                  })}
                  className="cr-target-branch"
                  required
                >
                  <Select
                    showSearch
                    dataSource={this.state.branches.map((item) => ({
                      label: item.name,
                      value: item.name,
                    }))}
                    {...init('target_branch', {
                      initValue: this.state.target_branch,
                      rules: [
                        {
                          required: true,
                          message: intl.get({
                            id: 'code-assets.createCRModal.uiless-create-mr-modal.ThisParameterIsRequired',
                            defaultMessage: '该项为必填项',
                          }),
                        },
                      ],
                      props: {
                        onChange: (value) => {
                          this.onTargetBranchChange(value);
                        },
                      },
                    })}
                  />
                </Form.Item>
              </div>
              <Form.Item
                label={intl.get({
                  id: 'code-assets.createCRModal.uiless-create-mr-modal.Title',
                  defaultMessage: '标题',
                })}
                required
                help={
                  this.field.getState('title') === 'error' ? (
                    this.field.getError('title')
                  ) : (
                    <div className="new-cr-title-help">
                      <div>
                        {intl.get({
                          id: 'code-assets.createCRModal.uiless-create-mr-modal.SupportedTitlePrefix',
                          defaultMessage: '支持标题前缀',
                        })}
                      </div>
                      <div className="wip">[WIP]</div>
                      <div>
                        {intl.get({
                          id: 'code-assets.createCRModal.uiless-create-mr-modal.IdentifyUnfinishedMergeRequestsTo',
                          defaultMessage:
                            '标识未完成的合并请求，避免开发中的代码被合并，可随时移除标识。',
                        })}
                      </div>
                    </div>
                  )
                }
              >
                <Input
                  placeholder={intl.get({
                    id: 'code-assets.createCRModal.uiless-create-mr-modal.EnterATitle',
                    defaultMessage: '请输入标题',
                  })}
                  {...init('title', {
                    initValue: this.state.title,
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.createCRModal.uiless-create-mr-modal.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                      { validator: this.nameValidator },
                    ],
                  })}
                  maxLength={256}
                  hasLimitHint
                />
              </Form.Item>
              <Form.Item
                label={intl.get({
                  id: 'code-assets.createCRModal.uiless-create-mr-modal.Reviewer',
                  defaultMessage: '评审人',
                })}
                className="formlabel-member-trigger"
              >
                <MemberTrigger
                  useRecommendMember={defaultReviewerList && defaultReviewerList.length}
                  recommendList={defaultReviewerList}
                  useExtraMember="project"
                  useProjectMember
                  pathResourceId={projectId}
                  onChange={this.onMemberChange}
                  value={this.state.assigneeIdDataSource}
                  align="cl br"
                  followTrigger={false}
                  multiple
                  uiless_config={uiless_config}
                  defaultList={
                    defaultReviewerList && defaultReviewerList.length
                      ? defaultReviewerList
                      : 'recommend'
                  }
                />

                {checkMes ? (
                  <Message
                    type="warning"
                    title={checkMes.msg}
                    shape="addon"
                    style={{ position: 'relative', top: '-3px' }}
                  />
                ) : null}
              </Form.Item>
              <Form.Item
                label={intl.get({
                  id: 'code-assets.createCRModal.uiless-create-mr-modal.Description',
                  defaultMessage: '描述',
                })}
              >
                <MdEditor
                  placeholder={intl.get({
                    id: 'code-assets.createCRModal.uiless-create-mr-modal.EnterADescription',
                    defaultMessage: '请输入描述',
                  })}
                  size="small"
                  onChangevalue={this.onChangevalue}
                  noAutoFocus
                  textareaStyle={{ height: '64px', padding: '4px 8px' }}
                  uiless_config={this.props.uiless_config}
                  projectId={this.state.projectId}
                  initValue={this.state.description}
                />
              </Form.Item>
              {getFeature('project.associated_projex_workitem') && this.state.projectId && (
                <Form.Item
                  label={
                    <span>
                      {intl.get({
                        id: 'code-assets.createCRModal.uiless-create-mr-modal.AssociatedContent',
                        defaultMessage: '关联内容',
                      })}
                    </span>
                  }
                >
                  <AssociatePanel
                    plugin={{ type: 'codeup-task', tbHost: uiless_config.tbHost }}
                    container={{
                      type: 'task',
                      target: 'merge_request',
                      // 任务中新建MR，传当前taskId
                      id: this.props.associateId,
                    }}
                    style={{ width: '100%' }}
                    uiless_config={{
                      ...window.UILessConfig,
                      codeupTrack: track,
                      useBy: 'mr',
                    }}
                    onChange={(items) => {
                      const workitem_ids = items.map((item) => {
                        return item._id;
                      });
                      this.setState({
                        workitem_ids: workitem_ids.join(','),
                      });
                    }}
                  />
                </Form.Item>
              )}
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}
      </React.Fragment>
    );
  }
}
